import {BadRequestException, Inject, Injectable} from '@nestjs/common';
import {CreateBookDto} from "./dto/create-book.dto";
import {DbService} from "../db/db.service";
import {UpdateBookDto} from "./dto/update-book.dto";
import { Book } from './entities/book.entity';
function randomNum() {
    return Math.floor(Math.random() * 1000000);
}

@Injectable()
export class BookService {
    @Inject()
    dbService: DbService;
    async list(name: string){
        const books: Book[] = await this.dbService.read();
        return name ? books.filter(book => {
            return book.name.includes(name);
        }) : books;
    }

    async findById(id: number){
        const books: Book[] = await this.dbService.read();
        return books.find(book => book.id === id);
    }

    async create(createBookDto: CreateBookDto){
        const books: Book[] = await this.dbService.read();

        const book = new Book();
        book.id = randomNum();
        book.name = createBookDto.name;
        book.author = createBookDto.author;
        book.description = createBookDto.description;
        book.cover = createBookDto.cover;

        books.push(book);

        await this.dbService.write(books);
        return book;
    }

    async update(updateBookDto: UpdateBookDto){
        const books: Book[] = await this.dbService.read();

        const foundBook = books.find(book => book.id === updateBookDto.id);

        if (!foundBook){
            throw new BadRequestException('没有找到该图书');
        }

        foundBook.name = updateBookDto.name;
        foundBook.author = updateBookDto.author;
        foundBook.cover = updateBookDto.cover;
        foundBook.description = updateBookDto.description;

        await this.dbService.write(books);
        return foundBook;
    }

    async delete(id: number) {
        const books: Book[] = await this.dbService.read();  // 1. 读取所有书籍数据
        const index = books.findIndex(book => book.id === id);  // 2. 查找要删除的书籍的索引

        if (index === -1) {  // 3. 如果找不到该书籍
            throw new BadRequestException('该图书不存在');  // 4. 抛出异常或返回错误信息
        }

        // 5. 如果找到书籍，删除它
        books.splice(index, 1);

        // 6. 写回数据库
        await this.dbService.write(books);
    }

}
